<template>
  <div class="app-container">
    <!-- 概览统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-content">
            <div class="overview-icon online">
              <i class="el-icon-success"></i>
            </div>
            <div class="overview-info">
              <div class="overview-value">{{ overviewData.onlineDevices || 0 }}</div>
              <div class="overview-label">在线设备</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-content">
            <div class="overview-icon offline">
              <i class="el-icon-error"></i>
            </div>
            <div class="overview-info">
              <div class="overview-value">{{ overviewData.offlineDevices || 0 }}</div>
              <div class="overview-label">离线设备</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-content">
            <div class="overview-icon total">
              <i class="el-icon-monitor"></i>
            </div>
            <div class="overview-info">
              <div class="overview-value">{{ overviewData.totalDevices || 0 }}</div>
              <div class="overview-label">设备总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card">
          <div class="overview-content">
            <div class="overview-icon data">
              <i class="el-icon-data-line"></i>
            </div>
            <div class="overview-info">
              <div class="overview-value">{{ overviewData.todayDataCount || 0 }}</div>
              <div class="overview-label">今日数据量</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示区域 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span>能耗排行榜</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshEnergyRanking">刷新</el-button>
          </div>
          <div id="energyRankingChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span>设备状态分布</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshStatusChart">刷新</el-button>
          </div>
          <div id="statusChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时监控表格 -->
    <el-card class="mt-4">
      <div slot="header" class="clearfix">
        <span>实时监控数据</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="refreshRealtimeData">刷新</el-button>
      </div>
      <el-table :data="realtimeData" v-loading="loading" style="width: 100%">
        <el-table-column prop="deviceCode" label="设备编码" width="120"></el-table-column>
        <el-table-column prop="deviceName" label="设备名称" width="150"></el-table-column>
        <el-table-column prop="power" label="功率(kW)" width="100">
          <template slot-scope="scope">
            <span>{{ (scope.row.data && scope.row.data.power || 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="voltage" label="电压(V)" width="100">
          <template slot-scope="scope">
            <span>{{ (scope.row.data && scope.row.data.voltage || 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="current" label="电流(A)" width="100">
          <template slot-scope="scope">
            <span>{{ (scope.row.data && scope.row.data.current || 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="temperature" label="温度(℃)" width="100">
          <template slot-scope="scope">
            <span>{{ (scope.row.data && scope.row.data.temperature || 0).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.data && scope.row.data.status === 'ONLINE' ? 'success' : 'danger'">
              {{ scope.row.data && scope.row.data.status === 'ONLINE' ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间">
          <template slot-scope="scope">
            <span>{{ scope.row.data && scope.row.data.ts ? parseTime(scope.row.data.ts) : '-' }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { getOverviewStatistics, getEnergyRanking, getRealtimeMonitorData } from "@/api/energy/statistics";
import { getDeviceOnlineStatistics } from "@/api/energy/device";
import * as echarts from 'echarts';

export default {
  name: "Dashboard",
  data() {
    return {
      loading: false,
      overviewData: {},
      realtimeData: [],
      energyRankingChart: null,
      statusChart: null,
      timer: null
    };
  },
  created() {
    this.loadOverviewData();
    this.loadRealtimeData();
    this.loadEnergyRanking();
    this.loadStatusChart();
    
    // 设置定时刷新
    this.timer = setInterval(() => {
      this.loadOverviewData();
      this.loadRealtimeData();
    }, 30000); // 30秒刷新一次
  },
  mounted() {
    this.initCharts();
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    if (this.energyRankingChart) {
      this.energyRankingChart.dispose();
    }
    if (this.statusChart) {
      this.statusChart.dispose();
    }
  },
  methods: {
    /** 加载概览数据 */
    loadOverviewData() {
      getOverviewStatistics().then(response => {
        this.overviewData = response.data || {};
      });
    },
    
    /** 加载实时数据 */
    loadRealtimeData() {
      this.loading = true;
      getRealtimeMonitorData().then(response => {
        this.realtimeData = response.data || [];
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    
    /** 加载能耗排行榜 */
    loadEnergyRanking() {
      const endTime = new Date();
      const startTime = new Date(endTime.getTime() - 7 * 24 * 60 * 60 * 1000); // 最近7天
      
      getEnergyRanking({
        energyType: 'ELECTRIC',
        startTime: startTime.toISOString(),
        endTime: endTime.toISOString(),
        limit: 10
      }).then(response => {
        this.updateEnergyRankingChart(response.data || []);
      });
    },
    
    /** 加载状态图表 */
    loadStatusChart() {
      getDeviceOnlineStatistics().then(response => {
        this.updateStatusChart(response.data || {});
      });
    },
    
    /** 初始化图表 */
    initCharts() {
      this.energyRankingChart = echarts.init(document.getElementById('energyRankingChart'));
      this.statusChart = echarts.init(document.getElementById('statusChart'));
    },
    
    /** 更新能耗排行榜图表 */
    updateEnergyRankingChart(data) {
      if (!this.energyRankingChart) return;
      
      const option = {
        title: {
          text: '设备能耗排行榜(最近7天)',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.device_code || ''),
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '能耗(kWh)'
        },
        series: [{
          data: data.map(item => item.total_consumption || 0),
          type: 'bar',
          itemStyle: {
            color: '#409EFF'
          }
        }]
      };
      
      this.energyRankingChart.setOption(option);
    },
    
    /** 更新状态图表 */
    updateStatusChart(data) {
      if (!this.statusChart) return;
      
      const option = {
        title: {
          text: '设备状态分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [{
          name: '设备状态',
          type: 'pie',
          radius: '50%',
          data: [
            { value: data.online || 0, name: '在线设备' },
            { value: data.offline || 0, name: '离线设备' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      
      this.statusChart.setOption(option);
    },
    
    /** 刷新方法 */
    refreshEnergyRanking() {
      this.loadEnergyRanking();
    },
    
    refreshStatusChart() {
      this.loadStatusChart();
    },
    
    refreshRealtimeData() {
      this.loadRealtimeData();
    }
  }
};
</script>

<style scoped>
.overview-card {
  margin-bottom: 20px;
}

.overview-content {
  display: flex;
  align-items: center;
}

.overview-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.overview-icon.online {
  background-color: #67C23A;
}

.overview-icon.offline {
  background-color: #F56C6C;
}

.overview-icon.total {
  background-color: #409EFF;
}

.overview-icon.data {
  background-color: #E6A23C;
}

.overview-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.overview-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.mt-4 {
  margin-top: 20px;
}

.mb-4 {
  margin-bottom: 20px;
}
</style>
